package org.example.crop.controller;

import org.example.crop.domain.Crop;
import org.example.crop.domain.Plant;
import org.example.crop.domain.Type;
import org.example.crop.service.CropService;
import org.example.crop.service.PlantService;
import org.example.crop.service.TypeService;
import org.example.crop.util.JwtUtils;
import org.example.crop.util.MinioUtils;
import org.example.crop.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("crop")
public class CropController {
    @Autowired
    private CropService cropService;
    @Autowired
    private MinioUtils minioUtils;
    @Autowired
    private TypeService typeService;
    @Autowired
    private PlantService plantService;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping("list")
    public Result cropList(){
        List<Crop> list = cropService.getList();
        return Result.success(list);
    }

    @RequestMapping("types")
    public Result getTypes(){
        List<Type> list = typeService.list();
        return Result.success(list);
    }

    @RequestMapping("plan")
    public Result plan(){
        List<Plant> list = plantService.list();
        return Result.success(list);
    }

    @RequestMapping("addCrop")
    public Result addCrop(@RequestBody Crop crop){
        Boolean b1 = redisTemplate.opsForValue().setIfAbsent(crop.getName()+crop.getCreateDate(), 1, 5, TimeUnit.MINUTES);
        if(!b1){
            System.out.println(crop.getName()+crop.getCreateDate()+"=============================");
            return Result.fail("该作物已存在,请勿重复提交");
        }
        String token = request.getHeader("token");
        Map map = (Map) JwtUtils.parseToken(token);
        Integer uid = (Integer) map.get("id");
        System.out.println(uid);
        crop.setUserId(uid);
        Date date = new Date();
        crop.setCreateDate(date);
        boolean b = cropService.save(crop);
        return b?Result.success():Result.fail();
    }

}
